package com.gitee.apanlh.util.net.http.handler.body;

import com.gitee.apanlh.exp.HttpBodyParseException;
import com.gitee.apanlh.util.net.http.HttpBody;
import com.gitee.apanlh.util.net.http.HttpClient;
import com.gitee.apanlh.util.net.http.HttpRequest;
import com.gitee.apanlh.util.net.http.HttpUrl;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;

import java.util.Map;

/**
 * 	HTTPBody请求体解析
 * 	<br>查询参数请求
 * 	<br>将改变URL参数
 * 	
 * 	@author Pan
 */
public class HttpBodyQueryParamParseStrategy implements HttpBodyParseStrategy {
	
	@Override
	public HttpRequest parse(HttpRequest httpRequest, HttpClient httpClient) throws HttpBodyParseException {
		return toQueryParams(httpRequest);
	}
	
	/**	
	 * 	转换至查询参数形式
	 * 	
	 * 	@author Pan
	 * 	@param 	httpRequest	HTTP请求对象
	 * 	@return	HttpRequest
	 */
	@SuppressWarnings("unchecked")
	HttpRequest toQueryParams(HttpRequest httpRequest) {
		HttpUrl url = httpRequest.getUrl();
		HttpBody httpBody = httpRequest.getBody();
		boolean hasParamUrlEncode = httpRequest.getConfig().hasParamUrlEncode();
		Object requestBody = httpBody.getRequestBody();
		Map<String, ?> paramMap;
		
		if (requestBody == null) {
			return httpRequest;
		}
		
		if (httpBody.isRequestBodyMap()) {
			paramMap = (Map<String, ?>) requestBody;
		} else {
			paramMap = ClassConvertUtils.toLinkedHashMap(requestBody);
		}
		
		url.append(KEY_PARAM).append(toNameValuePair(paramMap, hasParamUrlEncode));
		httpBody.setRequestBody(null);
		httpRequest.setBody(httpBody);
		return httpRequest;
	}
}
